import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../controllers/favorites_controller.dart';
import '../../../config/app_branding.dart';
import '../../../data/models/wiki_config.dart';

class FavoritesView extends GetView<FavoritesController> {
  const FavoritesView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: Container(
        decoration: BoxDecoration(
          gradient: AppBranding.primaryGradient,
        ),
        child: Obx(() => _buildBody()),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: Text(
        '我的收藏',
        style: TextStyle(
          fontSize: 20.sp,
          fontWeight: FontWeight.w600,
          color: Colors.white,
        ),
      ),
      backgroundColor: Colors.transparent,
      elevation: 0,
      flexibleSpace: Container(
        decoration: BoxDecoration(
          gradient: AppBranding.primaryGradient,
        ),
      ),
      actions: [
        if (controller.favorites.isNotEmpty)
          IconButton(
            icon: const Icon(Icons.clear_all, color: Colors.white),
            onPressed: _showClearAllDialog,
            tooltip: '清空收藏',
          ),
      ],
    );
  }

  Widget _buildBody() {
    if (controller.isLoading.value) {
      return const Center(
        child: CircularProgressIndicator(color: Colors.white),
      );
    }

    if (controller.favorites.isEmpty) {
      return _buildEmptyState();
    }

    return _buildFavoritesList();
  }

  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(32.w),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.favorite_border,
              size: 80.r,
              color: Colors.white.withOpacity(0.6),
            ),
            SizedBox(height: 24.h),
            Text(
              '暂无收藏',
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 12.h),
            Text(
              '在浏览Wiki时点击收藏按钮\n将内容添加到这里',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.white.withOpacity(0.8),
                height: 1.5,
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 32.h),
            ElevatedButton(
              onPressed: () => Get.back(),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.white,
                foregroundColor: AppBranding.primaryColor,
                padding: EdgeInsets.symmetric(
                  horizontal: 32.w,
                  vertical: 12.h,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.r),
                ),
              ),
              child: Text(
                '去浏览Wiki',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFavoritesList() {
    return ListView.builder(
      padding: EdgeInsets.all(16.w),
      itemCount: controller.favorites.length,
      itemBuilder: (context, index) {
        final favorite = controller.favorites[index];
        return _buildFavoriteItem(favorite, index);
      },
    );
  }

  Widget _buildFavoriteItem(WikiItem item, int index) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(16.r),
          onTap: () => controller.openFavorite(item),
          child: Padding(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                // 图标
                Container(
                  width: 48.r,
                  height: 48.r,
                  decoration: BoxDecoration(
                    gradient: AppBranding.secondaryGradient,
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Icon(
                    _getItemIcon(item.category),
                    color: Colors.white,
                    size: 24.r,
                  ),
                ),
                SizedBox(width: 16.w),
                // 内容
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        item.name,
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: const Color(0xFF333333),
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      if (item.nameEn.isNotEmpty) ...[
                        SizedBox(height: 4.h),
                        Text(
                          item.nameEn,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: const Color(0xFF666666),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                      SizedBox(height: 4.h),
                      Text(
                        item.category,
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: AppBranding.primaryColor,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
                // 操作按钮
                PopupMenuButton<String>(
                  icon: Icon(
                    Icons.more_vert,
                    color: const Color(0xFF999999),
                    size: 20.r,
                  ),
                  onSelected: (value) {
                    switch (value) {
                      case 'remove':
                        _showRemoveDialog(item);
                        break;
                      case 'share':
                        controller.shareFavorite(item);
                        break;
                    }
                  },
                  itemBuilder: (context) => [
                    const PopupMenuItem(
                      value: 'remove',
                      child: Row(
                        children: [
                          Icon(Icons.delete_outline, size: 18),
                          SizedBox(width: 8),
                          Text('移除收藏'),
                        ],
                      ),
                    ),
                    const PopupMenuItem(
                      value: 'share',
                      child: Row(
                        children: [
                          Icon(Icons.share_outlined, size: 18),
                          SizedBox(width: 8),
                          Text('分享'),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  IconData _getItemIcon(String category) {
    switch (category.toLowerCase()) {
      case 'character':
      case '角色':
        return Icons.person;
      case 'item':
      case '物品':
        return Icons.inventory;
      case 'location':
      case '地点':
        return Icons.place;
      case 'quest':
      case '任务':
        return Icons.assignment;
      case 'skill':
      case '技能':
        return Icons.star;
      case 'recipe':
      case '配方':
        return Icons.restaurant;
      default:
        return Icons.article;
    }
  }

  void _showRemoveDialog(WikiItem item) {
    Get.dialog(
      AlertDialog(
        title: const Text('移除收藏'),
        content: Text('确定要将「${item.name}」从收藏中移除吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.removeFromFavorites(item);
            },
            child: const Text(
              '移除',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  void _showClearAllDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('清空收藏'),
        content: const Text('确定要清空所有收藏吗？此操作无法撤销。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.clearAllFavorites();
            },
            child: const Text(
              '清空',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }
}